package com.leizhi.demo.monitor.config;

import com.leizhi.demo.monitor.utils.SingletonObjectMapperUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Description Redis 配置类
 * @Version ${MavenProject.version}
 * @Author leizhi
 * @Date 2025/4/27 10:00
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        // 创建模板
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        // 设置序列化工具
        StringRedisSerializer key = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> value = new Jackson2JsonRedisSerializer<>(Object.class);
        value.setObjectMapper(SingletonObjectMapperUtil.getInstance());

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(key);
        template.setValueSerializer(value);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(key);
        template.setHashValueSerializer(value);
        template.afterPropertiesSet();

        return template;
    }

}
